<?php

/**
 * 全局函数和设置
 *
 * @package    01CMS
 * @subpackage system
 * @author     rolong at vip.qq.com
 * @version    1.0.0
 * @link       http://www.01cms.com
 */

//设定编码
header('Content-Type: text/html; charset=utf-8');

//设置时区
if (function_exists('date_default_timezone_set'))
{
    date_default_timezone_set('Asia/Shanghai');
}

//定义时间常量
define('TIME', time());

if (! function_exists('date_default_timezone_set'))
{

    function json_encode ($data)
    {
        return lib('Services_JSON')->encode($data);
    }
}

if (! defined('DIRECTORY_SEPARATOR'))
{
    define('DIRECTORY_SEPARATOR', strtoupper(substr(PHP_OS, 0, 3) == 'WIN') ? '\\' : '/');
}

/**
 * 自动加载[类文件]
 * 
 * @param string $className
 * @return void
 */
function __autoload ($className)
{
    $type = (strpos($className, 'Model') > 0) ? 'model' : 'lib';
    
    if (file_exists(APP_PATH . '/' . $type . '/' . $className . '.php'))
    {
        require_once (APP_PATH . '/' . $type . '/' . $className . '.php');
    }
    else if (file_exists(SYS_PATH . '/' . $type . '/' . $className . '.php'))
    {
        require_once (SYS_PATH . '/' . $type . '/' . $className . '.php');
    }
    else if (file_exists(APP_PATH . '/' . $type . '/' . $className . '/' . $className . '.php'))
    {
        require_once (APP_PATH . '/' . $type . '/' . $className . '/' . $className . '.php');
    }
    else if (file_exists(SYS_PATH . '/' . $type . '/' . $className . '/' . $className . '.php'))
    {
        require_once (SYS_PATH . '/' . $type . '/' . $className . '/' . $className . '.php');
    }
    else
    {
        throw new Exception("Class '{$className}' not found!");
    }
}

/**
 * 加载类库
 *
 * @param string $libName
 * @param mix $param
 * @return object
 */
function lib ($libName, $param = NULL)
{
    return $GLOBALS['Load']->_class($libName, $param);
}

/**
 * 加载模型
 *
 * @param string $libName
 * @param mix $param
 * @return object
 */
function model ($modelName, $param = NULL)
{
    return $GLOBALS['Load']->_class($modelName . 'Model', $param);
}

/**
 * 加载数据
 *
 * @param string $libName
 * @param mix $param
 * @return object
 */
function data ($fileName)
{
    return $GLOBALS['Load']->_file($fileName, 'data');
}

/**
 * 加载配置文件
 *
 * @param string $libName
 * @param mix $param
 * @return object
 */
function config ($fileName)
{
    return $GLOBALS['Load']->_file($fileName, 'config');
}

/**
 * 输出错误并中止程序运行
 * 
 * @param string $message 错误提示信息
 * @return void
 */
function showError ($message = '')
{
    if ($message == '404')
    {
        $message = '您访问的页面不存在！';
    }
    
    $message = '<span class="error">' . $message . '</span>';
    
    include SYS_PATH . '/view/error.php';
    exit();
}

/**
 * 输出提示信息
 * 
 * @param string $message 提示信息
 * @return void
 */
function showInfo ($message = '')
{
    include SYS_PATH . '/view/info.php';
    exit();
}

/**
 * postResponse
 * 
 * @param string $message
 * @param string $goUrl
 * @param string $stayTime
 * @param string $javascript
 * @return void
 */
function responseToParent ($message, $goUrl = '', $stayTime = 3, $javascript = FALSE)
{
    $info = json_encode(array('message'=>$message, 'goUrl'=>$goUrl, 'stayTime'=>$stayTime, 'javascript'=>$javascript));
    echo '<script language="javascript" type="text/javascript">window.parent.postResponse(' . $info . ');</script>';
    exit();
}

/**
 * response
 * 
 * @param string $message
 * @param string $success
 * @param string $javascript
 * @return void
 */
function response ($message, $success = FALSE, $javascript = FALSE)
{
    header('Cache-Control:no-cache, must-revalidate');
    echo json_encode(array('message'=>$message, 'success'=>$success, 'javascript'=>$javascript));
    exit();
}

/**
 * 对引号添加或去除反斜杠
 * 
 * @param string $svar
 * @param string $type (add | slash)
 * @param string $force
 * @return void
 */
function slashQuotes (&$svar, $type = 'add', $force = false)
{
    if (! get_magic_quotes_gpc() || $force)
    {
        if (is_array($svar))
        {
            foreach ($svar as $_k => $_v)
                $svar[$_k] = slashQuotes($_v, $type, $force);
        }
        else
        {
            $svar = ($type == 'add') ? addslashes($svar) : stripslashes($svar);
        }
    }
    return $svar;
}

/**
 * 跳转
 * 
 * @param string $url
 * @return void
 */
function redirect ($url)
{
    if (strpos($url, 'http://') !== 0)
    {
        $url = BOOT_URL . '/' . $url;
    }
    
    header('location:' . $url);
}

/**
 * 获取客户端IP
 * 
 * @return string
 */
function getIp ()
{
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown'))
    {
        $ip = getenv('HTTP_CLIENT_IP');
    }
    elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown'))
    {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    }
    elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown'))
    {
        $ip = getenv('REMOTE_ADDR');
    }
    elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
    {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    
    return $ip;
}

/**
 * 获取加密字符串
 * 
 * @param string $var
 * @return string
 */
function encrypt ($var)
{
    return md5(Base::i()->Load->config['secret'] . $var);
}

/**
 * 新建文件夹
 * 
 * @param string $folder
 * @param int $mode (0764)
 * @return bool
 */
function makeDirs ($folder, $mode = 0764)
{
    if (file_exists($folder))
    {
        return false;
    }
    
    $mkfolder = (substr($folder, 0, 1) == "/") ? '/' : '';
    $folder = explode("/", $folder);
    
    for ($i = 0; isset($folder[$i]); $i ++)
    {
        $parentFolder = $mkfolder;
        $mkfolder .= empty($folder[$i]) ? '' : $folder[$i] . "/";
        if (is_writable($parentFolder))
        {
            if (! file_exists($mkfolder) && $i > 1)
            {
                mkdir($mkfolder, $mode);
            }
        }
    }
    
    return TRUE;
}

/**
 * 检测是否非空
 * 
 * @param string $var
 * @return bool
 */
function notEmpty ($var)
{
    return (! empty($var));
}

/**
 * 清空目录
 * 
 * @param string $dir
 * @return string
 */
function clearDirs ($dir)
{
    $dirHandle = opendir($dir);
    
    $msg = '';
    
    while ($fileName = readdir($dirHandle))
    {
        if ($fileName != "." && $fileName != "..")
        {
            if (is_dir("$dir/$fileName"))
            {
                clearDirs($dir . "/" . $fileName);
                
                if (@rmdir("$dir/$fileName"))
                {
                    $msg .= "成功删除:";
                }
                else
                {
                    $msg .= "删除失败:";
                }
                
                $msg .= " -- <strong>$dir/$fileName</strong>";
                $msg .= "<br />";
            
            }
            else
            {
                if (@unlink("$dir/$fileName"))
                {
                    $msg .= "成功删除:";
                }
                else
                {
                    $msg .= "删除失败:";
                }
                
                $msg .= " -- $dir/$fileName";
                $msg .= "<br />";
            }
        }
    }
    
    closedir($dirHandle);
    
    return $msg;
}

/**
 * 获取当前URL
 * 
 * @return string
 */
function getCurUrl ()
{
    if (! empty($_SERVER["REQUEST_URI"]))
    {
        return $_SERVER["REQUEST_URI"];
    }
    else
    {
        $scriptName = $_SERVER["PHP_SELF"];
        
        if (empty($_SERVER["QUERY_STRING"]))
        {
            return $scriptName;
        }
        else
        {
            return $scriptName . "?" . $_SERVER["QUERY_STRING"];
        }
    }
}

/**
 * 中文截取(UTF-8)
 * 
 * @param string $str
 * @param int $start
 * @param int $length
 * @return string
 */
function cnSubstr ($str, $start, $length)
{
    if (function_exists('mb_substr'))
    {
        return mb_substr($str, $start, $length, 'UTF-8');
    }
    $arr = array();
    preg_match_all("/./u", $str, $arr);
    return implode('', array_slice($arr[0], $start, $length));
}

/**
 * 获取缩略图
 *
 * @param string $url
 * @return string
 */
function getThumb ($url)
{
    if(empty($url))
    {
	    return PUBLIC_DIR . '/common/image/no_thumb.gif';
    }
    $setting = data('uploadSetting');
    $pos = strrpos($url, '.');
    return substr($url, 0, $pos) . $setting['thumbMarker'] . substr($url, $pos);
}

//END
